# coding=utf-8
import time
import win32gui
import win32ui
import win32con
import cv2

# WIDTH = 1920
# HEIGHT = 1080

WIDTH = 450
HEIGHT = 230
SCREEN_FILENAME = "./1.png"

hwnd = 0 # 软件的窗口句柄
hwndDC = win32gui.GetWindowDC(hwnd) # 获取软件窗口的设备
mfcDC = win32ui.CreateDCFromHandle(hwndDC) # 声明了一个和软件窗口设备同一类型的可访问的设备
saveDC = mfcDC.CreateCompatibleDC() # 创建一个能够与可访问设备资源同步的设备接口api
saveBitMap = win32ui.CreateBitmap() # bitmap是一个位图, 它可以渲染资源, 展示成一个图片
# print(dir(saveBitMap))
# print(type(saveBitMap.GetBitmapBits))
# print(type(saveBitMap))
saveBitMap.CreateCompatibleBitmap(mfcDC, WIDTH, HEIGHT) # 创建了一个与可访问的软件窗口设备同步的设备
saveDC.SelectObject(saveBitMap)


def window_capture():  # local desktop  image
    # saveDC.BitBlt((0, 0), (WIDTH, HEIGHT), mfcDC, (0, 0), win32con.SRCCOPY)
    saveDC.BitBlt((0,0), (WIDTH, HEIGHT), mfcDC, (170, 220), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, SCREEN_FILENAME)


def find_image_cv(obj_path, src_path):
    source = cv2.imread(src_path)
    template = cv2.imread(obj_path)
    result = cv2.matchTemplate(source, template, cv2.TM_CCOEFF_NORMED)
    pos_start = cv2.minMaxLoc(result)[3]
    test = cv2.minMaxLoc(result)
    x = int(pos_start[0]) + int(template.shape[1] / 2)
    y = int(pos_start[1]) + int(template.shape[0] / 2)
    similarity = cv2.minMaxLoc(result)[1]
    print(similarity)
    if similarity < 0.86:
        return (-1, -1)
    else:
        # print("pass")
        return [(x, y), (x, y)]


if '__main__' == __name__:
    find_image_list = ["./f1.png", './f2.png']
    while True:
        bt = time.time()
        window_capture()
        et = time.time()
        for item in find_image_list:
            src_path = SCREEN_FILENAME  # （当前页面）
            obj_path = item  # （需要点击的地方）
            p, q = find_image_cv(obj_path, src_path)
            print("当前需要查找的图片（%s）的坐标：" % (item), q)

        time.sleep(0.5)
